package com.firesyde.gwt.persistence.guice.bdb;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.sleepycat.bind.serial.ClassCatalog;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.firesyde.gwt.persistence.*;
import com.firesyde.gwt.persistence.bdb.BerkeleyDBDataManager;
import com.firesyde.gwt.persistence.client.StorableDAO;

/**
 * Simple module to inject Berkeley DB Java Edition database/environment/catalog objects
 * @author dan
 *
 */
public class BerkeleyDBModule extends AbstractModule {

	private String envLocation;
	private String dbName;

	private BerkeleyDBModule() {
		
	}
	
	public BerkeleyDBModule(String envLocation, String dbName) {
		super();
		this.envLocation = envLocation;
		this.dbName = dbName;
	}
	
	@Override
	protected void configure() {
		
	    EnvironmentConfig envConfig = new EnvironmentConfig();
	    envConfig.setAllowCreate(true);
	    
	    try {
			Environment myDbEnvironment = new Environment(new File(envLocation), envConfig);
			
			//bind this instance to the environment
			bind(Environment.class).toInstance(myDbEnvironment);
			
			// Create a provider for the database
		    Provider<Database> dbProvider = new DatabaseProvider(myDbEnvironment, dbName);
			
		    //get databases from the database provider
		    bind(Database.class).toProvider(dbProvider);
		    
		    Provider<ClassCatalog> classCatalogProvider = new ClassCatalogProvider(dbProvider);
		    
		    //create a single ClassCatalog instance
		    bind(ClassCatalog.class).toProvider(classCatalogProvider);
		    
		} catch (DatabaseException e) {
			System.out.println("Whoops - bad db environment: "+e.getMessage());
			e.printStackTrace();
		}
		
		//bind the data manager to a Berkeley DB Data Manager
		bind(IDataManager.class).to(BerkeleyDBDataManager.class);
		
		//logging XXX totally lazy!
		bind(Logger.class).toInstance(LoggerFactory.getLogger(BerkeleyDBModule.class));
	}

}
